package cn.mrcode.fd.blog.task;

import cn.mrcode.fd.blog.dto.stat.Stat;
import cn.mrcode.fd.blog.dto.stat.StatCal;
import cn.mrcode.fd.utils.log.track.LogTrackTemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 统计task
 * @author : zhuqiang
 * @version : V1.0
 * @date : 2016/1/25 21:20
 */
public class StatTask implements Runnable {
    private static Logger LOGGER = LoggerFactory.getLogger(TagHanderTask.class);
    public static LinkedBlockingDeque<Stat> deque = new LinkedBlockingDeque<Stat>(); //待处理队列

    /**
     * 缓存map,用于缓存一定时间的统计数量，然后每隔一段时间就往数据库中插入统计数据
     * key = id,value = stat 统计对象
     */
    public static ConcurrentHashMap<String, StatCal> hz = new ConcurrentHashMap();

    @Override
    public void run() {
        String apiName = "[统计task]";
        LOGGER.info(LogTrackTemplateUtil.svStart(apiName));
        for (; ; ) {
            try {
                Stat stat = deque.take();
                int type = stat.getType();
                String id = stat.getId();
                if (hz.containsKey(id)) {
                    StatCal statCal = hz.get(id);
                    int num = statCal.getCount();
                    statCal.setCount(num+1);
                } else {
                    StatCal statCal = new StatCal();
                    statCal.setId(id);
                    statCal.setType(type);
                    statCal.setCount(1);
                    hz.put(id, statCal);
                }
            } catch (InterruptedException e) {
                LOGGER.error(LogTrackTemplateUtil.svMsg(apiName,"出错:%s",e.getMessage()));
            }
        }
    }
}
